package com.fingard.dsp.bank.directbank.lcbip01;

import com.fingard.FGBiz;
import com.fingard.constant.Format;
import com.fingard.dsp.bank.directbank.DirectBase;
import com.fingard.dsp.bank.directbank.fngrd01.util.StringHelper;
import com.fingard.net.ITcpClient;
import com.fingard.net.TcpPortClient;
import com.fingard.net.TcpReceiver;
import com.fingard.net.WebRequest;
import com.fingard.util.FtpUtil;
import com.fingard.util.TransIDHelper;
import com.fingard.xml.XmlTextWriter;

import java.io.File;
import java.io.FileOutputStream;
import java.util.Date;

/**
 *
 * @author marlon
 * @date 2018/9/10
 */
public class LCBIP01Base extends DirectBase implements ITcpClient {

    private static TransIDHelper idHelper = new TransIDHelper(1, 99);

    @Override
    public void getContentLength(TcpReceiver p_receiver) throws Exception {
        if (p_receiver.contentLength == -1) {
            String tmpCharset = getCharset();
            String tmpRecNow = new String(p_receiver.recBytes, 0, p_receiver.readedLength, tmpCharset);
            if (tmpRecNow.contains("</lcbank>")) {
                p_receiver.contentLength = p_receiver.readedLength;
                p_receiver.contentStartIndex = 0;
            }
        }
    }

    protected String getQryTransID() {
        Date tmpDateNow = new Date();
        return Format.Time6Format.format(tmpDateNow) + idHelper.getNextIDStr();
    }
    protected void writeCommonHeader(XmlTextWriter xmlWriter, LCBIP01Header p_bankHeader) throws Exception{
        /**
         * <?xmlversion="1.0"encoding="gb2312" ?>
         <lcbank>
         <head>
         <BankNo>50</BankNo>
         <TuxName> QueryBankSlip </TuxName>
         <ReqSeqNo>00001234</ReqSeqNo>
         <ReqDate>20171202</ReqDate>
         <ReqTime>173909</ReqTime>
         </head>
         * */
        xmlWriter.writeStartDocByDeclaration("<?xml version=\"1.0\" encoding=\""+getCharset()+"\"?>");
        xmlWriter.writeStartElement("lcbank");
        xmlWriter.writeStartElement("head");
        xmlWriter.writeElementString("BankNo", "50");
        xmlWriter.writeElementString("TuxName", p_bankHeader.TuxName);
        xmlWriter.writeElementString("ReqSeqNo", p_bankHeader.ReqSeqNo);
        xmlWriter.writeElementString("ReqDate", Format.Date8Format.format(new Date()));
        xmlWriter.writeElementString("ReqTime", Format.Time6Format.format(new Date()));

    }

    protected String getCharset(){
        return getBankConfig().getCharset("utf-8");
    }



    protected String[] sendToBank(String p_reqStr) throws Exception {

        String[] retStr = new String[]{"", ""};

        WriteBankUrlLogLn( "请求银行的地址"+bankFront.serverIP + ":" + bankFront.serverPort);
        p_reqStr = p_reqStr.replaceAll("[\\r\\n]","")+"\r\n";
//        p_reqStr = "<?xml version=\"1.0\" encoding = \""+getCharset()+"\"?><lcbank><head><BankNo>50</BankNo><TuxName>Balance</TuxName><ReqSeqNo>45116692</ReqSeqNo><ReqDate>20181218</ReqDate><ReqTime>120000</ReqTime></head><body><CustCode>11110003008</CustCode><AccNo>1010300820020001</AccNo><AccContry></AccContry><AccPriv></AccPriv><AccCity>湖北</AccCity><CurType>01</CurType><HisDate></HisDate></body></lcbank>\r\n";
        WriteBankLogStep2(p_reqStr);
        //发送银行前置
        TcpPortClient tmpClient = new TcpPortClient(bankFront.serverIP, Integer.parseInt(bankFront.serverPort), this);
        tmpClient.timeoutMil=300000;
        TcpReceiver tmpReceiver = tmpClient.sendMessage(p_reqStr,getCharset());
        retStr[0] = tmpReceiver.connState;
        retStr[1] = tmpReceiver.getFullString(getCharset());
        if(StringHelper.isNullOrEmpty(retStr[1])){
        	retStr[1] = tmpReceiver.getConnMsg();
        }
        WriteBankLogStep3(retStr[1]);
        return retStr;
    }
    protected String[] sendToBankNoLog(String p_reqStr,StringBuilder sbLog) throws Exception {
        String[] retStr = new String[]{"", ""};
        sbLog.append(Format.DateTimeSSSFormat.format(new Date()) + " 发送银行的地址：\r\n");
        sbLog.append( "请求银行的地址"+bankFront.serverIP + ":" + bankFront.serverPort);
        sbLog.append("\r\n\r\n");
        p_reqStr = p_reqStr.replaceAll("[\\r\\n]","")+"\r\n";
        sbLog.append(Format.DateTimeSSSFormat.format(new Date()) + " 2.发送银行的报文：\r\n");
        sbLog.append(p_reqStr);
        sbLog.append("\r\n\r\n");
        TcpPortClient tmpClient = new TcpPortClient(bankFront.serverIP, Integer.parseInt(bankFront.serverPort), this);
        tmpClient.timeoutMil=300000;
        TcpReceiver tmpReceiver = tmpClient.sendMessage(p_reqStr,getCharset());
        retStr[0] = tmpReceiver.connState;
        retStr[1] = tmpReceiver.getFullString(getCharset());
        if(StringHelper.isNullOrEmpty(retStr[1])){
            retStr[1] = tmpReceiver.getConnMsg();
        }
        sbLog.append(Format.DateTimeSSSFormat.format(new Date()) + " 3.银行返回的报文：\r\n");
        sbLog.append(retStr[1]);
        sbLog.append("\r\n\r\n");
        return retStr;
    }
    //上送格式为json格式
    protected  String[] sendToATS(String jsonData) throws Exception{
        String[] retStr = new String[]{"",""};
        WriteBankLogLn("2.提交ATS的地址："+ FGBiz.dspCenter.dspSet.receiptPushServerUrl);


        //发送银行前置
        WebRequest tmpRequest = new WebRequest(FGBiz.dspCenter.dspSet.receiptPushServerUrl);
        tmpRequest.setConnectTimeout(60000);
        tmpRequest.setRequestProperty("connection", "Close");
        tmpRequest.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
        String charsetName = getCharset();
        WriteBankLogLn("3.推送给ATS的json数据"+jsonData);
        byte[] tmpWriteBytes = jsonData.getBytes(charsetName);
        retStr = tmpRequest.upload(tmpWriteBytes, charsetName);
        WriteBankLogLn("4.返回的数据"+retStr[1]);

        return retStr;
    }

    protected void singleNumMapping(String askNumber, String reqSeq) throws Exception {
        FileOutputStream fos = null;
        try {
            String filePath = FGBiz.dspCenter.dspSet.dataDirPath + File.separator + "LCBIPSingle" + File.separator + askNumber + ".txt";
            File batFile = new File(filePath);
            if (!batFile.getParentFile().exists()) {
                batFile.getParentFile().mkdirs();
            }
            String fileContent = "";
            String newFileContent = askNumber + ":" + reqSeq;
            if (!batFile.exists()) {
                batFile.createNewFile();
            } else {
                fileContent = FtpUtil.getTextFromFile(filePath, getCharset());
                if (fileContent.contains(newFileContent)) {
                    return;
                }
            }
            fos = new FileOutputStream(batFile);
            fos.write(fileContent.concat(newFileContent).getBytes());
            fos.close();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (fos != null) {
                fos.close();
            }
        }
    }
}
